/*
Copyright (c) 2012 the VATSIM Connector project

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

#include "planes.h"
#include <XPLMGraphics.h>
#include <XPLMPlanes.h>
#include <vector>
#include <cmath>
#include <cassert>

#ifdef APL
#include <OpenGL/gl.h>
#else
#include <GL/gl.h>
#endif

XPInnPlanes::XPInnPlanes()
: m_wantsControl(false),
  m_hasControl(false),
  m_drawCallback(xplm_Phase_Airplanes, true, std::tr1::bind(&XPInnPlanes::drawCallback, this)),
  m_drawBeforeGaugesCallback(xplm_Phase_Gauges, true, std::tr1::bind(&XPInnPlanes::drawBeforeGaugesCallback, this)),
  m_drawAfterGaugesCallback(xplm_Phase_Gauges, false, std::tr1::bind(&XPInnPlanes::drawAfterGaugesCallback, this))
{
}

XPInnPlanes::~XPInnPlanes()
{
  releaseControl();
}

void XPInnPlanes::init()
{
  m_taxonomy.reloadDesignators(xpinnGetResourcePath() + "doc8643.txt");
  m_taxonomy.reloadPlanes(xpinnGetResourcePath() + "opensceneryx.txt");
}

void XPInnPlanes::acquireControl()
{
  m_wantsControl = true;
  if (XPLMAcquirePlanes(0, &controlAvailableCallback, static_cast<void*>(this)))
  {
    m_hasControl = true;
    m_overrideDataRef1.setAll(std::vector<int>(XPINN_PLANE_OVERRIDES, 1));
    m_overrideDataRef2.setAll(std::vector<int>(XPINN_PLANE_OVERRIDES, 1));
    for (size_t i = 1; i < XPINN_PLANE_OVERRIDES; ++i) XPLMDisableAIForPlane(i);
    XPLMSetActiveAircraftCount(1);
    invalidateObjects();
  }
}

void XPInnPlanes::releaseControl()
{
  m_hasControl = m_wantsControl = false;
  m_overrideDataRef1.setAll(std::vector<int>(XPINN_PLANE_OVERRIDES, 0));
  m_overrideDataRef2.setAll(std::vector<int>(XPINN_PLANE_OVERRIDES, 0));
  XPLMSetActiveAircraftCount(1);
  XPLMReleasePlanes();
}

void XPInnPlanes::controlAvailableCallback(void* refcon)
{
  XPInnPlanes* self = static_cast<XPInnPlanes*>(refcon);
  if (self->m_wantsControl) self->acquireControl();
}

void XPInnPlanes::invalidateObjects()
{
  for (map_type::iterator it = m_map.begin(); it != m_map.end(); ++it)
  {
    it->second.m_model.unload();
  }
}

void XPInnPlanes::handleMessage(VconMsgPlanePosition const& msg)
{
  Plane& plane = m_map[msg.callsign];

  plane.m_mostRecentMsg = msg;
  plane.m_mostRecentMsgTime = XPLMGetElapsedTime();
}

void XPInnPlanes::updatePositions()
{
  if (! m_hasControl) return;

  float time = XPLMGetElapsedTime();
  std::vector<map_type::iterator> markedForRemoval;
  set_type tempTCASplanes;

  for (map_type::iterator it = m_map.begin(); it != m_map.end(); ++it)
  {
    Plane& plane = it->second;

    if (plane.m_mostRecentMsgTime < time - 1)
    {
      markedForRemoval.push_back(it);
    }
    else
    {
      update(plane);

      tempTCASplanes.insert(&plane);
    }
  }

  for (std::vector<map_type::iterator>::iterator it = markedForRemoval.begin();
       it != markedForRemoval.end();
       ++it)
  {
    //m_map.erase(*it);
  }

  m_TCASplanes.swap(tempTCASplanes);
}

void XPInnPlanes::drawBeforeGaugesCallback()
{
  if (! m_hasControl) return;

  size_t index = 0;
  for (set_type::iterator it = m_TCASplanes.begin();
       index < XPINN_PLANE_DATAREFS && it != m_TCASplanes.end();
       ++index, ++it)
  {
    m_datarefs.x(index, (*it)->m_drawInfo.x);
    m_datarefs.y(index, (*it)->m_drawInfo.y);
    m_datarefs.z(index, (*it)->m_drawInfo.z);
    m_datarefs.the(index, (*it)->m_drawInfo.pitch);
    m_datarefs.phi(index, (*it)->m_drawInfo.roll);
    m_datarefs.psi(index, (*it)->m_drawInfo.heading);
  }
  XPLMSetActiveAircraftCount(index + 1);
}

void XPInnPlanes::drawAfterGaugesCallback()
{
  if (! m_hasControl) return;

  XPLMSetActiveAircraftCount(1);
}

void XPInnPlanes::update(Plane& plane)
{
  if (! plane.m_model.isValid())
  {
    plane.m_model.load(m_taxonomy.getClosestMatch(plane.m_mostRecentMsg.aircraft, plane.m_mostRecentMsg.airline));
  }

  double x, y, z;
  XPLMWorldToLocal(plane.m_mostRecentMsg.lat, plane.m_mostRecentMsg.lon,
    xpinnFeetToMeters(double(plane.m_mostRecentMsg.alt)),
    &x, &y, &z);

  plane.m_drawInfo.x = x;
  plane.m_drawInfo.y = y;
  plane.m_drawInfo.z = z;
  plane.m_drawInfo.pitch = 0;
  plane.m_drawInfo.heading = plane.m_mostRecentMsg.hdg;
  plane.m_drawInfo.roll = 0;

  snapToGround(plane);
  deduceAnimState(plane);

  double userLat = m_latitudeDataRef.get();
  double userLon = m_longitudeDataRef.get();
  double userAlt = m_elevationDataRef.get();

  plane.m_distSqr = x*x + y*y + z*z;
  plane.m_inTCASRange = std::abs(xpinnMetersToFeet(userAlt) - plane.m_mostRecentMsg.alt) < 5050
    && xpinnGreatCircleDistance(userLat, userLon, plane.m_mostRecentMsg.lat, plane.m_mostRecentMsg.lon) < 50.5;
}

void XPInnPlanes::snapToGround(Plane& plane)
{
  //TODO if gear is down then impose minimum altitude = ground elevation,
  // and if height < A && speed < B then impose maximum altitude = ground elevation.
  // Let A be some smallish height like 20 ft and let B be slightly less than
  // the minumum V_r speed for the aircraft's wake turbulence category.
  // This is to avoid the common "aircraft taxiing above/below ground" problem.
}

void XPInnPlanes::deduceAnimState(Plane& plane)
{
  //TODO deduce heuristically certain parameters that are not provided by the connector,
  // like control surface deflections and selective lighting.
}

void XPInnPlanes::drawCallback()
{
  if (! m_hasControl) return;

  for (map_type::iterator it = m_map.begin(); it != m_map.end(); ++it)
  {
    draw(it->second);
  }
}

void XPInnPlanes::draw(Plane& plane)
{
  if (! plane.m_model.isValid()) return;

  plane.m_model.draw(plane.m_drawInfo);
}

XPInnPlanes::Plane::Plane()
{
  m_drawInfo.structSize = sizeof(m_drawInfo);
}